var app = getApp()

Page({
  data: {
    loaded: false,
    orderId: '',
    orderSource: '',
    haveReceived: null,
    haveRedEnvelope: null,
    giveAmount: ''
  },
  onLoad: function (options) {
    if (!options.orderId) {
      return app.toast.error('参数错误：缺少订单ID')
    }
    if (!options.userId) {
      return app.toast.error('参数错误：缺少用户ID')
    }
    if (!options.orderSource) {
      return app.toast.error('参数错误：缺少订单来源')
    }
    this.setData({
      orderId: options.orderId,
      userId: options.userId,
      orderSource: options.orderSource || 'online'
    })
    app.showLoading()
    app.ready(() => {
      this.getRedEnvelopeInfo()
    })
  },
  getRedEnvelopeInfo: function () {
    let params = {
      orderId: this.data.orderId,
      userId: this.data.userId,
    }
    params = {
      __zaofans: true,
      datas: JSON.stringify(params)
    }
    app.request('/yuanmai_we/redEnvelope/grab', params).then(res => {
      this.setData({
        haveReceived: res.haveReceived, //是否领过
        haveRedEnvelope: res.haveRedEnvelope, //是否抢完
        loaded: true
      })

      if (res.haveReceived === false && res.haveRedEnvelope === true) {
        this.redward()
      } else if (res.haveReceived === true) {
        this.setData({
          giveAmount: res.rewardAmount
        })
        app.toast.error('这是一个已抢过的红包哦！')
      }

    }, err => {
      app.toast.error(err)
    }).finally(app.hideLoading)
  },
  redward: function () {
    let params = {
      activityId: this.data.orderId,
      userId: this.data.userId,
      type: 'redEnvelope',
      orderSource: this.data.orderSource
    }
    params = {
      __zaofans: true,
      __openid: app.globalData.openID,
      uname: 'weappmall',
      datas: JSON.stringify(params)
    }
    app.request('/yuanmai_we/user/reward', params).then(res => {
      if (res.success) {
        this.setData({
          giveAmount: res.giveAmount,
          haveReceived: true //解决没领过有红包的页面不显示问题
        })
        app.getPrevPage().getCommentInfo()
      } else {
        app.toast.error(res.errMsg)
      }
    }, err => {
      app.toast.error(err)
    })
  },
  goHome: function () {
    wx.switchTab({
      url: '/pages/bread/breadindex'
    })
  }
})
